package www.cskaoyan.com.dao.JDBCUtils;

import java.sql.Connection;
import java.util.LinkedList;

public class ConnectionPool {

    static int INIT_SIZE = 10; // 默认初始化数据库连接数目
    static int MIN_SIZE = 3; // 最小数据库连接数目
    static int INCREMENT_SIZE = 5; // 数据库连接数目默认扩容增量
    static LinkedList<Connection> linkedList;// 数据库连接存储'容器'


    // 初始化数据库连接池
    static {
        linkedList = new LinkedList<Connection>();
        addCapacity(INIT_SIZE);
    }

    // 数据库连接池扩容
    public static void addCapacity(int count){
        if (count <= 0) {
            return;
        }

        for (int i = 0; i < count; i++) {
            linkedList.add(JDBCLoad.getConnection());
        }
    }

    // 获取数据库连接
    public static Connection getConnection(){
        if (linkedList.size() <=  MIN_SIZE){
            addCapacity(INCREMENT_SIZE);
        }
        Connection connection = linkedList.removeLast();

        return connection;
    }

    // 归还数据库连接
    public static void returnConnection(Connection connection){
        linkedList.addFirst(connection);
    }
}
